import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { click } from '@testing-library/user-event/dist/click';

import { Link, BrowserRouter } from 'react-router-dom';
import { Router, Route, Routes, Switch } from "react-router";
import Page1 from './component/Page1';
import Page3 from './component/Page3';
import Page2 from './component/Page2';
import { render } from '@testing-library/react';

// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(
//   <React.StrictMode>
//     <App />
//   </React.StrictMode>
// );

// const root = ReactDOM.createRoot(document.getElementById('root'));
// root.render(<h1>Hello, world!</h1>);

// It is my space!
function formatName(user){
    return user.firstName + ' ' + user.lastName;
}

function getGreeting(user){
    if(user){
        return <h1>Hello, {formatName(user)}!</h1>
    }
    return <h1>Hello, Stranger.</h1>
}

const user = {
    firstName: 'Harper',
    lastName: 'Perez',
};

const element = (
    <h1>
        Hello,{formatName(user)}
    </h1>
);

function Welcome(props){
    return <h1>Hello, {props.name}</h1>;
}

class WelcomeClass extends React.Component{
    render(){
        return <h1>Hello, {this.props.name}</h1>;
    }

}

const root = ReactDOM.createRoot(document.getElementById('body'))

root.render(
    getGreeting(user)
);

function tick(){
    const elementTick = (
        <div>
            <h1>Hello, World!</h1>
            <h2>It is {new Date().toLocaleTimeString()}.</h2>
        </div>
    );
    root.render(elementTick)
}

// setInterval(tick, 10000);

const elementWelcomeFunc = <Welcome name="Sara"></Welcome>;

function MyApp(){
    return(
        <div>
            <Welcome name="Sara"></Welcome>
            <Welcome name="Cahal"></Welcome>
            <Welcome name="Edite"></Welcome>

        </div>

    );
}

// function Clock(props){
//     return (
//         <div>
//             <h1>Hello, world!</h1>
//             <h2>It is {props.date.toLocaleTimeString()}.</h2>
//         </div>
//     );
// }

class Clock extends React.Component{
    constructor(props){
        super(props);
        this.state = {date: new Date()};
    }
    tick() {
        this.setState({
          date: new Date()
        });
    }
    componentDidMount(){
        this.timeID = setInterval(
            () => this.tick(),
            1000
        );
    }
    componentWillUnmount(){
        clearInterval(this.timeID);
    }
    render(){
        return (
            <div>
                <h1>Hello, world.</h1>
                <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
            </div>
        );
    }
}

function tick2(){
    root.render(<Clock />);
}

// setInterval(tick2, 1000);

const elementApp = <MyApp />;

const ahref = <a href='#' onClick="console.log('The link was clicked.'); return false">Click me!</a>;

function ActionLink(){

    function handleClick(e){
        e.preventDefault();
        console.log('The link was clicked.');
    }
    return (
        <a href='#' onClick={handleClick}>
            Click me!
        </a>
    );
}


class Toggle extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            id: 0,
            isToggleOn: true
        };
        this.handlerClick = this.handlerClick.bind(this);
    }
    handlerClick(id){
        this.setState(state => ({
            id: state.id + id,
            isToggleOn: !state.isToggleOn
        }));
        console.log(this.state.id);
    }

    handClick = (id) => {
        console.log(id);
        const value = this.state.id + id;
        this.setState(state => ({
            id : value,
            isToggleOn: !state.isToggleOn
        }));
    }

    render(){
        return (
            <div>
                <button onClick={this.handlerClick.bind(this, 1)}>
                    {this.state.isToggleOn?'ON':'OFF'} And this id is {this.state.id}!
                </button>
                <button onClick={this.handlerClick.bind(this, 2)}>
                    {this.state.isToggleOn?'ON':'OFF'} And this id is {this.state.id}!
                </button>
                <button onClick={this.handlerClick.bind(this, 3)}>
                    {this.state.isToggleOn?'ON':'OFF'} And this id is {this.state.id}!
                </button>
            </div>
        
        )
    }
}



// class Home extends React.Component{
 
// 	render(){
// 		return(
//             <BrowserRouter>
// 			<div>
// 				<p>This is Home!</p>
// 				<Routes>
//                     <Route path="/Page1/" element = {<Page1></Page1>}>
//                     </Route>
//                     <Route path="/Page2/" element = {<Page2></Page2>}>
//                     </Route>
//                     <Route path="/Page3/" element = {<Page3></Page3>}>
//                     </Route>
//                 </Routes>
// 			</div>
//             </BrowserRouter>
// 		);
// 	}
// }

function UserGreeting(props){
    return <h1>Welcome back!</h1>;
}

function GuestGreeting(props){
    return <h1>Please sign up.</h1>;
}

function Greeting(props){
    const isLoggedIn = props.isLoggedIn;
    if(isLoggedIn){
        return <UserGreeting />;
    }
    return <GuestGreeting />;

}

function LoginButton(props){
    return (
        <div>
            <button onClick={props.onClick}>Login!</button>
        </div>
    );
}

function LogouButton(props){
    return (
        <div>
            <button onClick={props.onClick}>
                Logout!
            </button>
        </div>
    );
}

class LoginController extends React.Component{
    constructor(props){
        super(props);
        this.state = {isLoggedIn: false};
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
    }

    handleLoginClick() {
        this.setState({isLoggedIn: true});

    }

    handleLogoutClick(){
        this.setState({isLoggedIn: false});
    }

    render(){
        const isLoggedIn = this.state.isLoggedIn;
        let button;
        if(isLoggedIn){
            button = <LogouButton  onClick={this.handleLogoutClick}/>
        }else{
            button = <LoginButton onClick={this.handleLoginClick}/>
        }
        return (
            <div>
                <Greeting isLoggedIn={isLoggedIn}/>
                {button}
            </div>
        );
    }
}

function MailBox(props){

    const unreadMessage = props.unreadMessage;
    return (
        <div>
            <h1>Hello!</h1>
            {
                unreadMessage.length > 0 &&
                <h2>
                    You have {unreadMessage.length} unread messages.
                </h2>
            }
        </div>
    );
}

const unreadMessage = ['React', 'Re: React', 'Re:Re: React'];

function WarnBanner(props){
    if(!props.warn){
        return null;
    }
    return (
        <div className='warning'>
            Warning
        </div>
    );
}

class Page extends React.Component{
    constructor(props){
        super(props);
        this.state = {showWarning : true};
        this.handleToggleClick = this.handleToggleClick.bind(this);
    }

    handleToggleClick(){
        this.setState(state => ({
            showWarning : !state.showWarning,
        }));
    }

    render(){
        return(
            <div>
                <WarnBanner warn={this.state.showWarning}></WarnBanner>
                <button onClick={this.handleToggleClick}>
                    {this.state.showWarning?'Hide':'Show'}
                </button>
            </div>
        );
    }
}

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) => (
    <li>{numbers}</li>
));

// function NumberList(props){
//     const numbers = props.numbers;
//     const listItems = numbers.map((number) => 
//         <li>{number}</li>
//     );
//     return (
//         <ul>{listItems}</ul>
//     );
// }

function ListItem(props){
    return (
        <li>{props.value}</li>
    );
}

function NumberList(props){
    const numbers = props.numbers;
    const ListItems = numbers.map((number) => (
        <ListItem key={number.toString()} value={number}></ListItem>
    ));
    return (
        <ul>
            {ListItems}
        </ul>
    );
}

function Blog(props){
    const sidebar = (
        <ul>
            {
                props.posts.map((post) => 
                    <li key={post.id}>
                        {post.title}
                    </li>
                )}
        </ul>
    );
    
    const content = props.posts.map((post) => (
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.context}</p>
        </div>
    ));

    return (
        <div>
            {sidebar}
            <hr/>
            {content}
        </div>
    );
}

const posts = [
    {id:1, title:'Hello World', context: 'Welcome to learning React!'},
    {id:2, title:'Installation', context: 'You can intsall React from npm.'}
];

class NameForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {value: ''};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({value: event.target.value});
    }

    handleSubmit(event){
        alert('提交的名字：' + this.state.value);
        event.preventDefault();
    }
    
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <label>
                    <input type="text" value={this.state.value} onChange={this.handleChange}></input>
                </label>
                <input type="submit" value="提交"></input>
            </form>
        );
    }
}

class EssayForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {value: '请撰写一篇关于DOM元素的你喜欢的文章.'};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({
            value: event.target.value
        });
    }

    handleSubmit(event){
        alert('提交的文章：' + this.state.value);
        event.preventDefault();
    }

    render(){
        return (
            <form onSubmit={this.handleSubmit}>
                <label>

                    <textarea type="text" value={this.state.value} onChange={this.handleChange}></textarea>
                </label>
                <input type="submit" value="提交"></input>

            </form>

        );
    }
}


class FlavorForm extends React.Component{
    constructor(props){
        super(props);
        this.state = {value: 'coconut'};
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event){
        this.setState({
            value: event.target.value,
        });
    }

    handleSubmit(event){
        alert('你喜欢的风味是：' + this.state.value);
        event.preventDefault();
    }

    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <label>
                    选择你喜欢的风味：
                    <select value={this.state.value} onChange={this.handleChange}>
                        <option value="grapefruit">葡萄柚</option>
                        <option value="lime">酸橙</option>
                        <option value="coconut">椰子</option>
                        <option value="mango">芒果</option>
                    </select>
                </label>
                <input type="submit" value="提交"></input>
            </form>
        );
    }
}


class Resercation extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isGoing: true,
            numberOfGuest: 2,
        };
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange(event){
        const target = event.target;
        const value = target.name === 'isGoing'?target.checked:target.value;
        const name = target.name;
        this.setState({
            [name]: value,
        }); 
    }

    render(){
        return (
            <form>
                <label>
                    参与：
                    <input checked={this.state.isGoing} type="checkbox" name="isGoing" onChange={this.handleInputChange}></input>
                </label>
                <br/>
                <label>
                    来宾人数：
                    <input name="numberOfGuest" type="number" value={this.state.numberOfGuest} onChange={this.handleInputChange}></input>
                </label>
            </form>
        );
    }
}

function BoilingVerdict(props){
    if(props.celsius >= 100){
        return <p>The water would boil.</p>
    }
    return <p>The water would not boil.</p>
}

const scaleNames = {
    'c': 'Celsius',
    'f': 'Fahrenheit'
}

class TemperatureInput extends React.Component{
    constructor(props){
        super(props);
        // this.state = {
        //     temperature: ''
        // };
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange(e){
        // this.setState({
        //     temperature: e.target.value
        // });
        this.props.onTemperatureChange(e.target.value);
    }

    render(){
        // const temperature = this.state.temperature;
        const temperature = this.props.temperature;
        const scale = this.props.scale
        return (
            <fieldset>
                <legend>Enter temperature in {scaleNames[scale]}：</legend>
                <input type="text" value={temperature} onChange={this.handleChange}></input>
                <BoilingVerdict celsius={parseFloat(temperature)}/>
            </fieldset>
        );
    }
}

class Calculator extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            temperature: '',
            scale: 'c'
        };
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    }
    handleCelsiusChange(temperature){
        this.setState({
            scale: 'c',
            temperature
        });
    }
    handleFahrenheitChange(temperature){
        this.setState({
            scale: 'f',
            temperature
        });
    }
    render(){
        const scale  = this.state.scale;
        const temperature = this.state.temperature;
        const celsius = scale === 'f'?tryConvert(temperature, toCelsius) : temperature;
        const fahrenheit = scale === 'c'?tryConvert(temperature, toFahrenheit) : temperature;
        return (
            <div>
                <TemperatureInput scale='c' temperature={celsius} onTemperatureChange={this.handleCelsiusChange}/>
                <TemperatureInput scale='f' temperature={fahrenheit} onTemperatureChange={this.handleFahrenheitChange}/>
                <BoilingVerdict celsius={parseFloat(celsius)}/>
            </div>
        );
    }
}

function toCelsius(fahrenheit){
    return (fahrenheit - 32) *5 /9;
}

function toFahrenheit(celsius){
    return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert){
    const input = parseFloat(temperature);
    if(Number.isNaN(input)){
        return '';
    }
    const output = convert(input);
    const rounded = Math.round(output * 1000) / 1000;
    return rounded.toString();
}

function FancyBorder(props) {
    return (
      <div className={'FancyBorder FancyBorder-' + props.color}>
        {props.children}
      </div>
    );
  }

  function WelcomeDialog() {
    return (
      <FancyBorder color="blue">
        <h1 className="Dialog-title">
          Welcome
        </h1>
        <p className="Dialog-message">
          Thank you for visiting our spacecraft!
        </p>
      </FancyBorder>
    );
  }

  function Contacts() {
    return <div className="Contacts" />;
  }

  function Chat() {
    return <div className="Chat" />;
  }

  function SplitPane(props) {
    return (
      <div className="SplitPane">
        <div className="SplitPane-left">
          {props.left}
        </div>
        <div className="SplitPane-right">
          {props.right}
        </div>
      </div>
    );
  }
  
  function App2() {
    return (
      <SplitPane
        left={
          <Contacts />
        }
        right={
          <Chat />
        } />
    );
  }


// root.render(elementWelcomeFunc);
// root.render(<Clock/>);
// root.render(<ActionLink></ActionLink>);
// root.render(<Home />);
// root.render(<Toggle />);
// root.render(<Greeting isLoggedIn={true}/>);
// root.render(<LoginController />);
// root.render(<MailBox unreadMessage={unreadMessage}/>);
// root.render(<Page />);
// root.render(
//     <ul>
//         {listItems}
//     </ul>
// )

// root.render(<NumberList numbers={numbers}></NumberList>);
// root.render(<NumberList numbers={numbers}></NumberList>);
// root.render(<Blog posts={posts}/>);

// root.render(<NameForm />);
// root.render(<EssayForm/>);
// root.render(<FlavorForm/>);
// root.render(<Resercation/>);
// root.render(<Calculator />);
// root.render(<WelcomeDialog />);
root.render(<App2 />);



// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

